﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using TB.Web.Nav;
using System.Web.Security;
//using Lenovo.KPL.BLL.Sys;
//using Lenovo.KPL.Common.Sys;


namespace ZkSurvey.Web.Helper
{
    /// <summary>
    /// UserHelper 的摘要说明
    /// </summary>
    public class UserHelper
    {
        private UserHelper() { }

        #region user


        public static string UserName
        {
            get
            {
                if (IsLogin())
                {
                    return User.UserName;
                }
                else
                {
                    ReLogin();
                }
                return null;
            }
        }

        public static string RealName
        {
            get
            {
                if (IsLogin())
                {
                    return User.RealName;
                }
                else
                {
                    ReLogin();
                }
                return null;
            }
        }

        //public static List<Program> SpPcrProgs
        //{
        //    get
        //    {
        //        if (IsLogin())
        //        {
        //            return User.SpPcrProgs;
        //        }
        //        else
        //        {
        //            ReLogin();
        //        }
        //        return null;
        //    }
        //}


        public static bool IsCpPcrMember
        {
            get
            {
                return User.IsCpPcrMember();
            }
        }

        public static bool IsCpPcrOwner
        {
            get
            {
                return User.IsCpPcrOwner();
            }
        }

        public static bool IsSpPcrMember(int progID)
        {
            return User.IsSpPcrMember(progID);
        }

        public static bool IsSpPcrOwner(int progID)
        {
            return User.IsSpPcrOwner(progID);
        }

        #endregion

        #region Log in / out

        public static bool Login(string username, string password)
        {
            SessionUser sUser = LoginPrivate(username, password);

            if (sUser != null)
            {
                return true;
            }
            else
                return false;
        }

        public static void LoginAnonymous()
        {
            //List<Program> viewList = new ProgramBl().GetProgramNonTP();
            //foreach (Program prog in viewList)
            //{
            //    prog.Title = null;      // 节省空间
            //}

            //SessionUser sUser = new SessionUser("Anonymous", "Anonymous",
            //    viewList, new List<Program>(), new List<Program>(), new List<Program>());

            //sUser.NavCfg = NavCfgMgr.GetUserNavCfg(new string[] {"1"});

            //User = sUser;
        }

        private static SessionUser LoginPrivate(string username, string password)
        {
            //UserBl userBl = new UserBl();
            //Common.Sys.User user = userBl.Login(username, password);
            //if (user != null)
            //{
            //    List<string> perms = new List<string>();

            //    perms.AddRange(user.Roles);

            //    List<TeamMember> tms = userBl.GetTeamMember(null, username);

            //    bool isCpPcrL = false;
            //    bool isCpPcrP = false;
            //    bool isCpPcrM = false;
            //    //bool isSpPcrL = false;
            //    //bool isSpPcrP = false;
            //    bool isSpPcrM = false;
            //    List<Program> spPcrProgs = null;
            //    Dictionary<int, bool> spPcrOwners = new Dictionary<int, bool>();       // is owner
            //    foreach (TeamMember tm in tms)
            //    {
            //        if (tm.ProgID == null)
            //        {
            //            if (tm.TeamCode == "ODTL")
            //                isCpPcrL = true;
            //            else if (tm.TeamCode == "ODTP")
            //                isCpPcrP = true;

            //            isCpPcrM = true;
            //        }
            //        else
            //        {
            //            if (tm.TeamCode == "ODTL")
            //            {
            //                //isSpPcrL = true;

            //                spPcrOwners[tm.ProgID.Value] = true;
            //            }
            //            else if (tm.TeamCode == "ODTP")
            //            {
            //                //isSpPcrP = true;

            //                spPcrOwners[tm.ProgID.Value] = true;
            //            }
            //            else
            //            {
            //                if (!spPcrOwners.ContainsKey(tm.ProgID.Value))
            //                    spPcrOwners[tm.ProgID.Value] = false;
            //            }

            //            isSpPcrM = true;
            //        }
            //    }

            //    spPcrProgs = new ProgramBl().GetProgram().FindAll(p => spPcrOwners.ContainsKey(p.ID));
            //    // Clear
            //    foreach (Program prog in spPcrProgs)
            //    {
            //        prog.ConceptExitDate = null;
            //        prog.PlanExitDate = null;
            //        prog.AnnounceDate4Pub = null;
            //        prog.AnnounceDate4Internal = null;
            //        prog.ShipSupportDate = null;
            //        prog.EndOfLifeDate = null;
            //        prog.EndOfProductionDate = null;
            //        prog.EndOfServiceDate = null;
            //        prog.OdtMailGroup = null;
            //        prog.ManagerMailGroup = null;
            //    }

            //    if (isCpPcrM) perms.Add("1024");        // Cp Pcr Member
            //    if (isSpPcrM) perms.Add("2048");        // Sp Pcr Member

            //    SessionUser sUser = new SessionUser(username, username,spPcrProgs,
            //        (isCpPcrL || isCpPcrP), isCpPcrM,
            //        spPcrOwners);

            //    sUser.NavCfg = NavCfgMgr.GetUserNavCfg(perms.ToArray());

            //    User = sUser;

            //    return sUser;
            //}
            //else
            //    return null;

            bool result = FormsAuthentication.Authenticate(username, password);

            if (result)
            {
                SessionUser sUser = new SessionUser(username, password, true, true, new Dictionary<int, bool>());
                List<string> perms = new List<string>();
                sUser.NavCfg = NavCfgMgr.GetUserNavCfg(perms.ToArray());
                User = sUser;

                FormsAuthentication.RedirectFromLoginPage(username, true);
                return sUser;
            }
            else
                return null;
        }

        public static void Logout()
        {
            HttpContext.Current.Session.Clear();
            System.Web.Security.FormsAuthentication.SignOut();
            HttpContext.Current.Response.Redirect("Login.aspx?r=f");
        }

        public static void ReLogin()
        {
            HttpContext.Current.Session["lastUrl"] = HttpContext.Current.Request.RawUrl;
            HttpContext.Current.Response.Redirect("Login.aspx");
        }

        public static void ReLogin(string lastUrl)
        {
            HttpContext.Current.Session["lastUrl"] = lastUrl;
            HttpContext.Current.Response.Redirect("Login.aspx");
        }

        public static bool IsLogin()
        {
            return (HttpContext.Current.Session["user"] != null);
        }

        public static void CheckLogin()
        {
            if (!IsLogin())
            {
                HttpContext.Current.Session["lastUrl"] = HttpContext.Current.Request.RawUrl;
                HttpContext.Current.Response.Redirect("Login.aspx");
            }
        }

        private static SessionUser User
        {
            get { return (SessionUser)HttpContext.Current.Session["user"]; }
            set { HttpContext.Current.Session["user"] = value; }
        }

        #endregion

        #region nav

        public static string GetVPKey()
        {
            string vpKey = HttpContext.Current.Request.QueryString["vp"];
            if (String.IsNullOrEmpty(vpKey))
                vpKey = HttpContext.Current.Items["defaultVP"].ToString();

            return vpKey;
        }
        public static TB.Web.Nav.VP GetVP()
        {
            TB.Web.Nav.VP vp = null;
            HttpContext currContext = HttpContext.Current;

            string vpKey = currContext.Request.QueryString["vp"];
            if (String.IsNullOrEmpty(vpKey))
                vpKey = currContext.Items["defaultVP"].ToString();
            if (!String.IsNullOrEmpty(vpKey))
            {
                if (currContext.Items.Contains(vpKey))
                    vp = (TB.Web.Nav.VP)(currContext.Items[vpKey]);
                else
                {
                    vp = User.NavCfg.GetVP(vpKey);

                    if (vp != null)
                        currContext.Items.Add(vpKey, vp);
                }
            }

            if (vp == null)
            {
                // 不存在或没有权限，引发异常
                throw new ApplicationException("很抱歉，您试图访问的网页不存在！");
            }

            return vp;
        }

        public static string GetVPUrl(string vpKey)
        {
            string url = User.NavCfg.GetVPUrl(vpKey);
            if (url == null)
                url = "#";
            return url;
        }

        /// <summary>
        /// 判断用户是否具有访问指定VP的权限
        /// </summary>
        /// <param name="funcTag">权限标记</param>
        /// <returns></returns>
        public static bool HasVPAccessPerm(string funcTag)
        {
            return GetVP().HasPerm(funcTag);
        }

        /// <summary>
        /// 检验用户是否具有指定的权限
        /// </summary>
        /// <param name="funcId">权限编码</param>
        /// <returns></returns>
        public static bool HasAccessPerm(string funcId)
        {
            return User.NavCfg.CheckFuncPerm(funcId);
        }

        /// <summary>
        /// 获取所有第一级节点
        /// </summary>
        /// <returns></returns>
        public static NavMenu[] GetRootMenus()
        {
            return User.NavCfg.GetRootMenus();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rootId">第一级节点ID</param>
        /// <returns></returns>
        public static NavMenu GetMenuTree(string rootId)
        {
            return User.NavCfg.GetMenu(rootId);
        }

        public static NavMenu GetMenu(string menuId)
        {
            return User.NavCfg.GetMenu(menuId);
        }

        #endregion

        #region SessionUser

        private class SessionUser
        {
            public SessionUser(string userName, string realName, //List<Program> spPcrProgs,
                bool isCpPcrMember, bool isCpPcrOwner,
                Dictionary<int, bool> spPcrProgsOwner)
            {
                this.userName = userName;
                this.realName = realName;
                //this.spPcrProgs = spPcrProgs;
                this.isCpPcrMember = isCpPcrMember;
                this.isCpPcrOwner = isCpPcrOwner;
                this.spPcrProgsOwner = spPcrProgsOwner;
            }

            private string userName;
            private string realName;
            private UserNavCfg navCfg;
            //private List<Program> spPcrProgs;
            private bool isCpPcrMember;
            private bool isCpPcrOwner;
            private Dictionary<int, bool> spPcrProgsOwner;

            public string UserName
            {
                get { return this.userName; }
            }
            public string RealName
            {
                get { return realName; }
            }
            public UserNavCfg NavCfg
            {
                get { return this.navCfg; }
                set { this.navCfg = value; }
            }
            //public List<Program> SpPcrProgs
            //{
            //    get { return spPcrProgs; }
            //    set { spPcrProgs = value; }
            //}
            public bool IsCpPcrMember()
            {
                return this.isCpPcrMember;
            }
            public bool IsCpPcrOwner()
            {
                return this.isCpPcrOwner;
            }

            public bool IsSpPcrMember(int progID)
            {
                return spPcrProgsOwner.ContainsKey(progID);
            }
            public bool IsSpPcrOwner(int progID)
            {
                return spPcrProgsOwner.ContainsKey(progID) &&
                    spPcrProgsOwner[progID];
            }
        }

        #endregion
    }
}
